package cn.net.trimmer.servlet.demo1.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtils {
	// 数据库全局配置文件
	private static final Properties prop = new Properties();
	// 线程局部变量,用于维护数据库连接
	private static final ThreadLocal<Connection> tol = new ThreadLocal<>();
	static {
		InputStream in = null;
		try {
			// 读取配置文件
			in = JdbcUtils.class.getResourceAsStream("/cn/net/trimmer/servlet/demo1/conf/db.properties");
			// 加载配置文件
			prop.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 数据库连接获取类
	 * 
	 * @return Connection 数据库连接
	 */
	public static Connection getConn() {
		// 从线程局部变量中去连接
		Connection conn = tol.get();
		try {
			// 如果本地变量没有连接则加载驱动并创建连接
			if (conn == null) {
				// 读取数据库配置参数
				String driver = prop.getProperty("oracle.driver");
				String url = prop.getProperty("oracle.url");
				String user = prop.getProperty("oracle.username");
				String password = prop.getProperty("oracle.password");
				// 加载驱动
				Class.forName(driver);
				// 获取连接
				conn = DriverManager.getConnection(url, user, password);
				// 存放到线程局部变量中
				tol.set(conn);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return conn;
	}

	/**
	 * jdbc释放资源工具类
	 * 
	 * @param rs   结果集
	 * @param stm  sql发送工具
	 * @param conn 数据库连接
	 */
	public static void release(ResultSet rs, Statement stm, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		if (stm != null) {
			try {
				stm.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		if (conn != null) {
			try {
				//关闭连接
				conn.close();
				//从线程局部变量中清除
				tol.remove();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}
}
